package com.ipzoe.common.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ipzoe.common.sms.config.AliSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

/**
 * 对接阿里短信验证码
 *
 * @author lenovo
 * @date 2019/12/07
 */
@Slf4j
public class AliSmsManager implements SmsManager {

    private AliSmsProperties properties;

    public AliSmsManager(AliSmsProperties properties) {
        this.properties = properties;
    }

    @Async
    @Override
    public void sendSms(String phone, String templateCode, Object... args) {
        DefaultProfile profile = DefaultProfile.getProfile(properties.getRegionId(), properties.getAccessKeyId(),
            properties.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(properties.getDomain());
        request.setSysVersion(properties.getVersion());
        request.setSysAction(properties.getAction());
        request.putQueryParameter("RegionId", properties.getRegionId());
        request.putQueryParameter("RegionId", properties.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", properties.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + args[0] + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("return msg: " + response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
            log.error("==> e1:", e);
        } catch (ClientException e) {
            e.printStackTrace();
            log.error("==> e2:", e);
        }

    }

}
